package com.example.lotterysystem.service.iml;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")
    private String localPath;


    @Override
    public String savePicture(MultipartFile pic) {
        File dir=new File(localPath);

        if(!dir.exists()){
            dir.mkdir();
        }

        //获取文件名
        String fileName=pic.getOriginalFilename();

        assert fileName!=null;


        //获取文件后缀

        String suffixName=fileName.substring(fileName.lastIndexOf('.'));


        fileName = UUID.randomUUID() + suffixName;
        try {
            pic.transferTo(new File(localPath + "/" + fileName));
        } catch (IOException e) {
            throw new
                    ServiceException(ServiceErrorCodeConstants.UPLOAD_PIC_ERROR);
        }
        return fileName;

    }
}
